//
//  VRBadgeButton.m
//  VRWeibo
//
//  Created by h3c-hp on 15/12/21.
//  Copyright © 2015年 h3c-mac. All rights reserved.
//

#import "YAYIBadgeButton.h"
#import "UIImage+VR.h"

#define VRBadgeButtonFontSize 11

@implementation YAYIBadgeButton


- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.hidden = YES;
        self.userInteractionEnabled = NO;
        
        [self setBackgroundImage:[UIImage resizedImageWithName:@"report_badge"] forState:UIControlStateNormal];
        //[self setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        self.titleLabel.font = [UIFont systemFontOfSize:VRBadgeButtonFontSize];
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        
    }

    return self;
}


/**
 *  传递badgeValue
 */
- (void)setBadgeValue:(NSString *)badgeValue
{
    _badgeValue = [badgeValue copy];
    
    if (badgeValue && [badgeValue integerValue] > 0) {
        self.hidden = NO;
        
        if (badgeValue.length > 2)
        {
            _badgeValue = @"99+";
        }
        
        // 设置标题
        [self setTitle:_badgeValue forState:UIControlStateNormal];
        
    }else{
        self.hidden = YES;
    }
    
    // 设置frame
    NSMutableDictionary *atrrs = [NSMutableDictionary dictionary];
    atrrs[NSFontAttributeName] = [UIFont systemFontOfSize:VRBadgeButtonFontSize];
    CGSize badgeTitleSize = [self.badgeValue sizeWithAttributes:atrrs];
    
    CGFloat badgeH = 20;
    
    CGFloat badgeW = badgeTitleSize.width + 8;
    if (badgeW < badgeH) {
        badgeW = badgeH;
    }
    
    //设置frame
//    self.size = CGSizeMake(30, badgeH);
//    self.center = self.center;
//    [self layoutIfNeeded];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    // 设置frame
    NSMutableDictionary *atrrs = [NSMutableDictionary dictionary];
    atrrs[NSFontAttributeName] = [UIFont systemFontOfSize:VRBadgeButtonFontSize];
    CGSize badgeTitleSize = [self.badgeValue sizeWithAttributes:atrrs];
    
    CGFloat badgeH = 20;
    
    CGFloat badgeW = badgeTitleSize.width + 8;
    if (badgeW < badgeH) {
        badgeW = badgeH;
    }
    
    //设置frame
//    self.size = CGSizeMake(badgeW, badgeH);
//    self.center = self.center;
    
    [self mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(badgeW);
        make.height.mas_equalTo(badgeH);
    }];
}


@end
